<template>
  <div class="report-detail">
    <el-page-header @back="goBack" title="返回">
      <template #content>
        <span class="page-title">测试报告详情</span>
      </template>
      <template #extra>
        <el-button-group>
          <el-button @click="exportReport('html')">
            <el-icon><document /></el-icon>
            导出HTML
          </el-button>
          <el-button @click="exportReport('pdf')">
            <el-icon><document /></el-icon>
            导出PDF
          </el-button>
          <el-button @click="exportReport('excel')">
            <el-icon><document /></el-icon>
            导出Excel
          </el-button>
        </el-button-group>
      </template>
    </el-page-header>

    <el-card style="margin-top: 20px;" v-loading="loading">
      <!-- 报告概览 -->
      <el-descriptions title="报告概览" :column="3" border>
        <el-descriptions-item label="报告名称">{{ report.name }}</el-descriptions-item>
        <el-descriptions-item label="项目名称">{{ report.project_name }}</el-descriptions-item>
        <el-descriptions-item label="生成时间">{{ report.created_at }}</el-descriptions-item>
        <el-descriptions-item label="总用例数">{{ report.total_cases }}</el-descriptions-item>
        <el-descriptions-item label="通过数">
          <span style="color: #67C23A; font-weight: bold;">{{ report.passed_cases }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="失败数">
          <span style="color: #F56C6C; font-weight: bold;">{{ report.failed_cases }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="通过率">
          <el-progress
            :percentage="report.pass_rate"
            :color="getPassRateColor(report.pass_rate)"
          />
        </el-descriptions-item>
        <el-descriptions-item label="总耗时">
          {{ formatDuration(report.total_duration) }}
        </el-descriptions-item>
        <el-descriptions-item label="平均响应时间">
          {{ report.avg_response_time }}ms
        </el-descriptions-item>
      </el-descriptions>

      <!-- 统计图表 -->
      <el-row :gutter="20" style="margin-top: 30px;">
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <span>用例执行结果分布</span>
            </template>
            <v-chart :option="pieChartOption" style="height: 300px;" />
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <span>响应时间分布</span>
            </template>
            <v-chart :option="barChartOption" style="height: 300px;" />
          </el-card>
        </el-col>
      </el-row>

      <!-- 用例详情 -->
      <el-divider>用例执行详情</el-divider>

      <el-tabs v-model="activeTab">
        <el-tab-pane label="全部用例" name="all">
          <el-table :data="filteredCases" border>
            <el-table-column prop="name" label="用例名称" min-width="200" />
            <el-table-column prop="method" label="方法" width="100">
              <template #default="{ row }">
                <el-tag :type="getMethodType(row.method)">{{ row.method }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="path" label="路径" min-width="200" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'passed' ? 'success' : 'danger'">
                  {{ row.status === 'passed' ? '通过' : '失败' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="response_time" label="响应时间" width="120">
              <template #default="{ row }">
                {{ row.response_time }}ms
              </template>
            </el-table-column>
            <el-table-column prop="status_code" label="状态码" width="100" />
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button size="small" @click="viewCaseDetail(row)">查看详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="通过用例" name="passed">
          <el-table :data="passedCases" border>
            <el-table-column prop="name" label="用例名称" min-width="200" />
            <el-table-column prop="method" label="方法" width="100">
              <template #default="{ row }">
                <el-tag :type="getMethodType(row.method)">{{ row.method }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="path" label="路径" min-width="200" />
            <el-table-column prop="response_time" label="响应时间" width="120">
              <template #default="{ row }">
                {{ row.response_time }}ms
              </template>
            </el-table-column>
            <el-table-column prop="status_code" label="状态码" width="100" />
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="失败用例" name="failed">
          <el-table :data="failedCases" border>
            <el-table-column prop="name" label="用例名称" min-width="200" />
            <el-table-column prop="method" label="方法" width="100">
              <template #default="{ row }">
                <el-tag :type="getMethodType(row.method)">{{ row.method }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="path" label="路径" min-width="200" />
            <el-table-column prop="error_message" label="错误信息" min-width="200" />
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button size="small" type="danger" @click="viewCaseDetail(row)">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 用例详情对话框 -->
    <el-dialog v-model="showCaseDetail" title="用例执行详情" width="80%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用例名称" :span="2">
          {{ currentCase.name }}
        </el-descriptions-item>
        <el-descriptions-item label="请求方法">
          {{ currentCase.method }}
        </el-descriptions-item>
        <el-descriptions-item label="请求路径">
          {{ currentCase.path }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentCase.status === 'passed' ? 'success' : 'danger'">
            {{ currentCase.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="响应时间">
          {{ currentCase.response_time }}ms
        </el-descriptions-item>
        <el-descriptions-item label="状态码">
          {{ currentCase.status_code }}
        </el-descriptions-item>
        <el-descriptions-item label="执行时间">
          {{ currentCase.executed_at }}
        </el-descriptions-item>
      </el-descriptions>

      <el-divider>请求信息</el-divider>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="请求头">
          <pre>{{ JSON.stringify(currentCase.request_headers, null, 2) }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="请求参数">
          <pre>{{ JSON.stringify(currentCase.request_body, null, 2) }}</pre>
        </el-descriptions-item>
      </el-descriptions>

      <el-divider>响应信息</el-divider>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="响应头">
          <pre>{{ JSON.stringify(currentCase.response_headers, null, 2) }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="响应体">
          <pre>{{ JSON.stringify(currentCase.response_body, null, 2) }}</pre>
        </el-descriptions-item>
      </el-descriptions>

      <el-divider v-if="currentCase.assertions">断言结果</el-divider>
      <el-table v-if="currentCase.assertions" :data="currentCase.assertions" border>
        <el-table-column prop="type" label="断言类型" width="150" />
        <el-table-column prop="expected" label="期望值" width="150" />
        <el-table-column prop="actual" label="实际值" width="150" />
        <el-table-column prop="result" label="结果" width="100">
          <template #default="{ row }">
            <el-tag :type="row.result ? 'success' : 'danger'">
              {{ row.result ? '通过' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="message" label="说明" min-width="200" />
      </el-table>

      <el-divider v-if="currentCase.error_message">错误信息</el-divider>
      <el-alert
        v-if="currentCase.error_message"
        :title="currentCase.error_message"
        type="error"
        :closable="false"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Document } from '@element-plus/icons-vue'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { getReport, exportReport as exportReportAPI } from '@/api'

use([
  CanvasRenderer,
  PieChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const activeTab = ref('all')
const showCaseDetail = ref(false)

const report = ref({
  name: '',
  project_name: '',
  created_at: '',
  total_cases: 0,
  passed_cases: 0,
  failed_cases: 0,
  pass_rate: 0,
  total_duration: 0,
  avg_response_time: 0,
  cases: []
})

const currentCase = ref({})

onMounted(() => {
  loadReport()
})

const loadReport = async () => {
  loading.value = true
  try {
    const reportId = route.params.id
    const result = await getReport(reportId)
    report.value = result.data || {}
  } catch (error) {
    ElMessage.error('加载报告失败')
  } finally {
    loading.value = false
  }
}

const filteredCases = computed(() => {
  return report.value.cases || []
})

const passedCases = computed(() => {
  return filteredCases.value.filter(c => c.status === 'passed')
})

const failedCases = computed(() => {
  return filteredCases.value.filter(c => c.status === 'failed')
})

const pieChartOption = computed(() => ({
  tooltip: {
    trigger: 'item'
  },
  legend: {
    bottom: '5%',
    left: 'center'
  },
  series: [
    {
      name: '用例执行结果',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: true,
        formatter: '{b}: {c} ({d}%)'
      },
      data: [
        { value: report.value.passed_cases, name: '通过', itemStyle: { color: '#67C23A' } },
        { value: report.value.failed_cases, name: '失败', itemStyle: { color: '#F56C6C' } }
      ]
    }
  ]
}))

const barChartOption = computed(() => {
  const cases = filteredCases.value
  const ranges = ['0-100ms', '100-500ms', '500-1000ms', '1000ms+']
  const data = [
    cases.filter(c => c.response_time < 100).length,
    cases.filter(c => c.response_time >= 100 && c.response_time < 500).length,
    cases.filter(c => c.response_time >= 500 && c.response_time < 1000).length,
    cases.filter(c => c.response_time >= 1000).length
  ]

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ranges
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '用例数',
        type: 'bar',
        data: data,
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  }
})

const viewCaseDetail = (caseData) => {
  currentCase.value = caseData
  showCaseDetail.value = true
}

const exportReport = async (format) => {
  try {
    const reportId = route.params.id
    const blob = await exportReportAPI(reportId, format)
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `report_${reportId}.${format}`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

const goBack = () => {
  router.back()
}

const formatDuration = (seconds) => {
  if (!seconds) return '-'
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return mins > 0 ? `${mins}分${secs}秒` : `${secs}秒`
}

const getPassRateColor = (rate) => {
  if (rate >= 90) return '#67C23A'
  if (rate >= 70) return '#E6A23C'
  return '#F56C6C'
}

const getMethodType = (method) => {
  const types = {
    GET: 'success',
    POST: 'primary',
    PUT: 'warning',
    DELETE: 'danger',
    PATCH: 'info'
  }
  return types[method] || ''
}
</script>

<style scoped>
.report-detail {
  padding: 20px;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
}

pre {
  background: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  max-height: 300px;
  overflow: auto;
  margin: 0;
}
</style>
